<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETF排行数据统计</title>
    <link rel="stylesheet" href="/css/antd.min.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #fff;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .header-title {
            margin: 0 0 20px 0;
            font-size: 20px;
            font-weight: 500;
            color: #333;
        }
        .stats-card {
            background-color: #fff;
            padding: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-item {
            text-align: center;
            padding: 20px;
            background-color: #fafafa;
            border-radius: 6px;
            border-left: 4px solid #1890ff;
        }
        .stat-number {
            font-size: 28px;
            font-weight: bold;
            color: #1890ff;
            margin-bottom: 8px;
        }
        .stat-label {
            font-size: 14px;
            color: #666;
        }
        .chart-container {
            height: 400px;
            margin-top: 20px;
        }
        .section-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
            margin: 0 0 20px 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
        }
        .growth-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .growth-card {
            background-color: #fafafa;
            padding: 16px;
            border-radius: 6px;
        }
        .growth-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 12px;
        }
        .growth-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .growth-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        .growth-item:last-child {
            border-bottom: none;
        }
        .growth-positive {
            color: #ff4d4f;
        }
        .growth-negative {
            color: #52c41a;
        }
        .action-section {
            margin-top: 20px;
            padding: 20px;
            background-color: #f0f2f5;
            border-radius: 6px;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #333;
        }
        .form-group input {
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
        }
        .btn-primary {
            padding: 8px 16px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary:hover {
            background-color: #40a9ff;
        }
        .btn-primary:disabled {
            background-color: #d9d9d9;
            cursor: not-allowed;
        }
        .message {
            margin-top: 16px;
            padding: 12px;
            border-radius: 4px;
            font-size: 14px;
        }
        .message-success {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .message-error {
            background-color: #fff1f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1 class="header-title">ETF排行数据统计</h1>
        <div style="display: flex; gap: 20px; color: #666;">
            <span><strong>总数据量：</strong><span th:text="${totalCount}">0</span> 条</span>
            <span><strong>最近更新：</strong><span th:text="${lastUpdateDate}">暂无数据</span></span>
        </div>
    </div>

    <div class="stats-card">
        <h2 class="section-title">ETF统计概览</h2>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-number" id="totalFundCount">0</div>
                <div class="stat-label">ETF基金总数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="positiveFundCount">0</div>
                <div class="stat-label">正增长基金数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="negativeFundCount">0</div>
                <div class="stat-label">负增长基金数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="avgGrowthRate">0.00</div>
                <div class="stat-label">平均涨跌幅(%)</div>
            </div>
        </div>
    </div>

    <div class="stats-card">
        <h2 class="section-title">ETF涨跌幅分布</h2>
        <div class="chart-container" id="distributionChart"></div>
    </div>

    <div class="stats-card">
        <h2 class="section-title">ETF涨跌幅排行</h2>
        <div class="growth-section">
            <div class="growth-card">
                <h3 class="growth-title">周涨跌幅TOP10</h3>
                <ul class="growth-list" id="weeklyTopList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </ul>
            </div>
            <div class="growth-card">
                <h3 class="growth-title">月涨跌幅TOP10</h3>
                <ul class="growth-list" id="monthlyTopList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </ul>
            </div>
            <div class="growth-card">
                <h3 class="growth-title">年涨跌幅TOP10</h3>
                <ul class="growth-list" id="yearlyTopList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </ul>
            </div>
        </div>
    </div>

    <div class="stats-card">
        <h2 class="section-title">数据管理</h2>
        <div class="action-section">
            <h3 style="margin-top: 0; margin-bottom: 16px; font-size: 16px; font-weight: 500;">清理历史数据</h3>
            <div class="form-group">
                <label for="cleanDateInput">清理日期（删除此日期之前的数据）：</label>
                <input type="date" id="cleanDateInput" value="">
            </div>
            <button id="cleanDataBtn" class="btn-primary" onclick="cleanData()">执行清理</button>
            <div id="cleanMessage" class="message" style="display: none;"></div>
        </div>
    </div>

    <script src="/js/jquery.min.js"></script>
    <script src="/js/antd.min.js"></script>
    <script src="/js/echarts.min.js"></script>
    <script>
        $(function() {
            // 设置默认清理日期为90天前
            const defaultCleanDate = new Date();
            defaultCleanDate.setDate(defaultCleanDate.getDate() - 90);
            const formattedDefaultCleanDate = defaultCleanDate.toISOString().split('T')[0];
            $('#cleanDateInput').val(formattedDefaultCleanDate);
            
            // 初始化图表
            initDistributionChart();
            
            // 加载数据
            loadStatisticsData();
        });
        
        // 初始化分布图表
        function initDistributionChart() {
            const chartDom = document.getElementById('distributionChart');
            const myChart = echarts.init(chartDom);
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: ['<-5%', '-5%~-3%', '-3%~-1%', '-1%~0%', '0%~1%', '1%~3%', '3%~5%', '>5%'],
                    axisLabel: {
                        interval: 0,
                        rotate: 30
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'ETF数量'
                },
                series: [
                    {
                        name: 'ETF数量',
                        type: 'bar',
                        data: [0, 0, 0, 0, 0, 0, 0, 0],
                        itemStyle: {
                            color: function(params) {
                                const colorList = [
                                    '#ff7875', '#ffa940', '#ffd591', '#fffbe6',
                                    '#f6ffed', '#d9f7be', '#95de64', '#52c41a'
                                ];
                                return colorList[params.dataIndex];
                            }
                        }
                    }
                ]
            };
            
            option && myChart.setOption(option);
            
            // 存储图表实例，便于后续更新
            window.distributionChart = myChart;
            
            // 响应式调整
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }
        
        // 加载统计数据
        function loadStatisticsData() {
            // 模拟数据，实际应用中应从后端获取
            // 这里直接调用数据列表接口获取当前日期的数据
            const currentDate = new Date().toISOString().split('T')[0];
            
            $.ajax({
                url: '/etfrank/dataList',
                type: 'GET',
                data: {
                    date: currentDate,
                    orderByField: 'weekly_growth_rate',
                    orderByDirection: 'desc',
                    limit: 100
                },
                success: function(response) {
                    if (response.success && response.data) {
                        const data = response.data;
                        updateStatistics(data);
                        updateDistributionChart(data);
                        updateGrowthRankings(data);
                    } else {
                        console.error('获取统计数据失败');
                    }
                },
                error: function() {
                    console.error('请求失败');
                }
            });
        }
        
        // 更新统计数据
        function updateStatistics(data) {
            const totalCount = data.length;
            let positiveCount = 0;
            let negativeCount = 0;
            let totalGrowthRate = 0;
            
            data.forEach(item => {
                const growthRate = item.dailyGrowthRate || 0;
                if (growthRate > 0) {
                    positiveCount++;
                } else if (growthRate < 0) {
                    negativeCount++;
                }
                totalGrowthRate += growthRate;
            });
            
            const avgGrowthRate = totalCount > 0 ? (totalGrowthRate / totalCount * 100).toFixed(2) : '0.00';
            
            $('#totalFundCount').text(totalCount);
            $('#positiveFundCount').text(positiveCount);
            $('#negativeFundCount').text(negativeCount);
            $('#avgGrowthRate').text(avgGrowthRate);
        }
        
        // 更新分布图表
        function updateDistributionChart(data) {
            // 计算各区间的ETF数量
            const distribution = {
                '-5%+': 0,  // <-5%
                '-5%~-3%': 0,
                '-3%~-1%': 0,
                '-1%~0%': 0,
                '0%~1%': 0,
                '1%~3%': 0,
                '3%~5%': 0,
                '5%+': 0    // >5%
            };
            
            data.forEach(item => {
                const growthRate = item.dailyGrowthRate || 0;
                const ratePercent = growthRate * 100;
                
                if (ratePercent < -5) {
                    distribution['-5%+']++;
                } else if (ratePercent < -3) {
                    distribution['-5%~-3%']++;
                } else if (ratePercent < -1) {
                    distribution['-3%~-1%']++;
                } else if (ratePercent < 0) {
                    distribution['-1%~0%']++;
                } else if (ratePercent <= 1) {
                    distribution['0%~1%']++;
                } else if (ratePercent <= 3) {
                    distribution['1%~3%']++;
                } else if (ratePercent <= 5) {
                    distribution['3%~5%']++;
                } else {
                    distribution['5%+']++;
                }
            });
            
            // 更新图表数据
            const chart = window.distributionChart;
            if (chart) {
                chart.setOption({
                    series: [{
                        data: [
                            distribution['-5%+'],
                            distribution['-5%~-3%'],
                            distribution['-3%~-1%'],
                            distribution['-1%~0%'],
                            distribution['0%~1%'],
                            distribution['1%~3%'],
                            distribution['3%~5%'],
                            distribution['5%+']
                        ]
                    }]
                });
            }
        }
        
        // 更新涨跌幅排行
        function updateGrowthRankings(data) {
            // 按周涨幅排序
            const weeklySorted = [...data].sort((a, b) => (b.weeklyGrowthRate || 0) - (a.weeklyGrowthRate || 0)).slice(0, 10);
            // 按月涨幅排序
            const monthlySorted = [...data].sort((a, b) => (b.monthlyGrowthRate || 0) - (a.monthlyGrowthRate || 0)).slice(0, 10);
            // 按年涨幅排序
            const yearlySorted = [...data].sort((a, b) => (b.yearGrowthRate || 0) - (a.yearGrowthRate || 0)).slice(0, 10);
            
            // 更新列表
            renderGrowthList('weeklyTopList', weeklySorted, 'weeklyGrowthRate');
            renderGrowthList('monthlyTopList', monthlySorted, 'monthlyGrowthRate');
            renderGrowthList('yearlyTopList', yearlySorted, 'yearGrowthRate');
        }
        
        // 渲染涨跌幅列表
        function renderGrowthList(elementId, data, fieldName) {
            const listElement = document.getElementById(elementId);
            listElement.innerHTML = '';
            
            if (data && data.length > 0) {
                data.forEach((item, index) => {
                    const growthRate = item[fieldName] || 0;
                    const percentStr = (growthRate * 100).toFixed(2) + '%';
                    const isPositive = growthRate > 0;
                    const isNegative = growthRate < 0;
                    
                    const listItem = document.createElement('li');
                    listItem.className = 'growth-item';
                    
                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = `${index + 1}. ${item.fundName || '-'}`;
                    nameSpan.style.fontSize = '14px';
                    nameSpan.style.width = '60%';
                    
                    const rateSpan = document.createElement('span');
                    rateSpan.textContent = percentStr;
                    rateSpan.className = isPositive ? 'growth-positive' : (isNegative ? 'growth-negative' : '');
                    rateSpan.style.fontWeight = '500';
                    rateSpan.style.fontSize = '14px';
                    
                    listItem.appendChild(nameSpan);
                    listItem.appendChild(rateSpan);
                    listElement.appendChild(listItem);
                });
            } else {
                const emptyItem = document.createElement('li');
                emptyItem.className = 'growth-item';
                emptyItem.style.justifyContent = 'center';
                emptyItem.style.color = '#999';
                emptyItem.textContent = '暂无数据';
                listElement.appendChild(emptyItem);
            }
        }
        
        // 清理数据
        function cleanData() {
            const beforeDate = $('#cleanDateInput').val();
            
            if (!beforeDate) {
                alert('请选择清理日期');
                return;
            }
            
            if (confirm(`确定要清理 ${beforeDate} 之前的所有ETF排行数据吗？此操作不可恢复！`)) {
                $('#cleanDataBtn').attr('disabled', true);
                $('#cleanMessage').hide();
                
                $.ajax({
                    url: '/etfrank/cleanData',
                    type: 'POST',
                    data: {
                        beforeDate: beforeDate
                    },
                    success: function(response) {
                        const messageElement = $('#cleanMessage');
                        if (response.success) {
                            messageElement.removeClass('message-error').addClass('message-success');
                            messageElement.text(response.message);
                            // 重新加载统计数据
                            loadStatisticsData();
                        } else {
                            messageElement.removeClass('message-success').addClass('message-error');
                            messageElement.text(response.message);
                        }
                        messageElement.show();
                    },
                    error: function() {
                        const messageElement = $('#cleanMessage');
                        messageElement.removeClass('message-success').addClass('message-error');
                        messageElement.text('清理数据失败，请稍后重试');
                        messageElement.show();
                    },
                    complete: function() {
                        $('#cleanDataBtn').attr('disabled', false);
                    }
                });
            }
        }
    </script>
</body>
</html>